import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import {CommonService} from '../../../../services/common.service'

interface NicsData  {
  id: number;
  name: string;
  portType: number;
  nicsUrn: string;
  disabled: boolean;

}
interface Data  {
  id: number;
  name: string;
  freeSizeGB: number;
  datastoreUrn: string;
  disabled: boolean;
}

interface Template{
  id: number;
  name: string;    //名称
  locationName: string;    //所在集群
  status: string;    //状态
  isBindingHost: boolean ;//     与主机绑定
  hostName: string;//所在主机
  urn: string;
  disabled: boolean;
}

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  diskList:any[]= [   //存储信息
    {
      datastoreUrn: "",   //硬盘主机
      name: "",     //所属数据存储
      quantityGB: 40,    //硬盘大小
      sequenceNum: 1,
      indepDisk: false,
      persistentDisk: true,
      isThin: false,
      pciType: "VIRTIO",   //总线类型
      volType: 1,         //类型  磁盘模式
      bootOrder: -1
    }
    ];

  nicsList:any[]= [   //存储信息
    {
      portGroupName: '',
      sequenceNum: 0,
      portGroupUrn: "",   //端口组
      virtIo: 1,   //virtio
      nicConfig: {
        vringbuf: 256,     //IO环大小
        queues: 1       // 队列数:
      },
      enableSecurityGroup: false,   // 安全组: 未开启
      bootOrder: -1
    }
  ];

  addTypeValue?: string;
  vmsLocationLabel ?: string;
  chooseResourcValueLabel ?: string;
  createType ?: string;
  quantityGB :0;
  datastoreInfo = {
    datastoreUrn:'',
    name:''
  };
  nicsInfo = {
    portGroupUrn : '',
    name : ''
  }
  TemplateInfo = {
    urn : '',
    name : '',
    detail: {}
  }

  templateId?: string;
  vmsId?: string;
  namePostfixIndex: 1;
  vmSize: 1;
  //虚拟机创建字段
  vms = {
    name: "123",     //名称
    description: "456",    //描述
    isBindingHost: false,
    parentObjUrn: "", //选择虚拟机位置
    location: "",   //选择计算资源
    hasSetStoreResAssignState: false,
    osOptions: {
      osType: "Windows",            //操作系统类型
      osVersion: 203                //操作系统版本号
    },
    isMultiDiskSpeedup: false,
    autoBoot: true,                 //创建完成后直接启动虚拟机
    vmConfig: {            //虚拟机配置
      cpu: {
        cpuPolicy: "shared",
        cpuThreadPolicy: "prefer",   // CPU线程绑定策略: 	prefer
        weight: 1000,               // 份额: 	1000
        reservation: 0,           // 预留(MHz): 	0
        quantity: 2,           //cpu核数
        limit: 0,            // 限制(MHz): 	0
        slotNum: 2,           // 插槽数: 	2
        coresPerSocket: 1      //每个插槽的内核数: 	1
      },
      memory: {
        quantityMB: 4096,   //内存
        reservation: 0,     // 预留(MB): 	0
        weight: 40960,   // 份额:
        hugePage: "4K",
        limit: 0,     // 限制(MB):
        unit: "GB"         //内存单位
      },
      numaNodes: 0,
      properties: {
        clockMode: "freeClock",
        bootFirmware: "BIOS",
        bootFirmwareTime: 0,
        bootOption: "disk",
        evsAffinity: false,
        isEnableHa: false,
        vmVncKeymapSetting: 7,
        isAutoUpgrade: true,
        attachType: false,
        isEnableMemVol: false,
        isEnableFt: false,
        cdRomBootOrder: -1,
        consoleLogTextState: false,
        isAutoAdjustNuma: false,
        consolelog: 1,
        secureVmType: "",
        dpiVmType: ""
      },
      graphicsCard: {    //显卡
        type: "cirrus",  //设备类型 类型   vga
        size: 4            // 显存(MB): 大小
      },
      disks: [   //存储信息
        {
          datastoreUrn: "",   //硬盘主机
          name: "",     //所属数据存储
          quantityGB: 40,    //硬盘大小
          sequenceNum: 1,
          indepDisk: false,
          persistentDisk: true,
          isThin: false,
          pciType: "VIRTIO",   //总线类型
          volType: 1,         //类型  磁盘模式
          bootOrder: -1
        }
      ],
      nics: [      //网卡
        {
          sequenceNum: 0,
          portGroupUrn: "urn:sites:3E1707BE:dvswitchs:1:portgroups:1",   //端口组
          virtIo: 1,   //virtio
          nicConfig: {
            vringbuf: 256,     //IO环大小
            queues: 1       // 队列数:
          },
          enableSecurityGroup: false,   // 安全组: 未开启
          bootOrder: -1
        }
      ]
    },
    floppyProtocol: "automatch",
    floppyFile: ""
  };



  sites = '';
  clusters = [];
  hosts = [];
  datastores = [];
  dvSwitchs = [];
  portGroups = [];

  linuxVersions = [];
  windowsVersions = [];
  otherVersions = [];

  checked = false;
  loading = false;
  indeterminate = false;
  listOfCurrentPageData: ReadonlyArray<Data> = [];
  setOfCheckedId = new Set<number>();

  setOfNicsCheckedId = new Set<number>();
  setOfTemplateCheckedId = new Set<number>();

  isVisible = false;
  nicsIsVisible = false;
  nicsIndex= 0 ;
  templateIsVisible = false;
  vmsIsVisible = false;
  selectedValue = null;

  osList = [];
  radioValue = 'A';
  propertyVms = '不使用自定义';
  demoValue = 3;
  listOfTemplate: Template [] = [ ]
  listOfData: Data [] = [
 /*   {
      id: 0,
      name: 'autoDS_linux-spqBpS',
      freeSizeGB: 5032,
      datastoreUrn: '虚拟化',
      disabled: false
    },
    {
      id: 1,
      name: 'autoDS_linux-spqBpS1',
      freeSizeGB: 1024,
      datastoreUrn: '虚拟化',
      disabled: false
    }*/

  ];

  listOfNicsData: NicsData [] = [
   /* {
      id: 0,
      name: 'autoDS_linux-spqBpS',
      portType: 5032,
      nicsUrn: '虚拟化',
      disabled: false
    }*/

  ];


  nzOptionsVmsLocatin  = [
  ];
  nzOptionsChooseResource  = [
  ];
  expandKeys = ['100', '1001'];
  chooseResourcValue?: string;
  public CSRF_HW:string = ''

  public VerifyCodeImage:string = 'test'

  public step: number = 1;

  public virtualStep: number = 1;

  public virtualType: number = 1;

  public virtualList: any = []

  public virtualSuccList:any = [{
    virtualTitle:'vm-name1',
    virtualNum:2
  }]
  // 正在登陆
  ShowLogin = false;
  // 用户名
  userName:'';
  // 密码
  userPassword:'';
  code:'';
  // 错误提示信息
  waringShow = false;
  // 错误提示信息内容
  waringMessage:[];
  constructor(public http : CommonService ,
    private message: NzMessageService) { }

  ngOnInit(): void {
    // 获取当前版本
   /* this.getVersion()*/
    this.getVerify()

    this.createType='创建新虚拟机';
  }
  add():void {
    this.step=this.step+1
    if(this.step==10)
    this.step=1
  }
  // 获取当前版本
  getVersion(){
    this.http.fcGet('/service/verify')
    .then((res:any)=>{
      console.log(res)
    })

  }
  // 登陆按钮
/*  LonginBtn(){
    if(this.userName && this.userPassword !== ''){
      this.ShowLogin = true;
      this.http.fcPost('/service/login/form',{
        "acceptLanguage": "zh-CN",
        "authUser": this.userName,
        "authKey": this.userPassword,
        "userType": "0",
        "authType": "0",
        "verification": this.code
      }).then((res:any)=>{
        this.ShowLogin = false;
        this.step = 2;
      })
    }else{
      return this.waringShow = true
    }
  }*/

  LonginBtn(){
    if(this.userName && this.userPassword !== ''){
      this.ShowLogin = true;
      this.http.axiosPost('/service/login/form',{
        "acceptLanguage": "zh-CN",
       // "authUser": this.userName,
       // "authKey": this.userPassword,
        "authUser": 'admin',
        "authKey": 'AI&RPA@2021',
        "userType": "0",
        "authType": "0",
        "verification": this.code
      }).then((res:any)=>{

        if(res.data.csrfToken!=''){
          this.CSRF_HW=res.data.csrfToken
          this.querySitesList(this.CSRF_HW);
          this.ShowLogin = false;
          this.step = 2;
        }


      })
    }else{
      return this.waringShow = true
    }
  }

  createVms(csrf, sites){
    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }
    this.http.axiosPostWithConfig('/service/sites/' + sites + '/vms', this.vms, config).then((res:any)=>{

    })
  }

  cloneVmsByTemplate(csrf, sites, id){

    this.vms['isTemplate']=false;
    this.vms['group']="";
    this.vms['vmCustomization'] = {
       "isUpdateVmPassword": true,
        "osType": "Windows"
    };

    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }
    let cloneURL = '/service/sites/' + sites + '/vms/' + id + '/action/clone';
    this.http.axiosPostWithConfig(cloneURL, this.vms, config).then((res:any)=>{

    })
  }

  cloneVms(csrf, sites, id){

    this.vms['isTemplate']=false;
    this.vms['group']="";
    this.vms['isLinkClone'] = false;

    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }
    let cloneURL = '/service/sites/' + sites + '/vms/' + id + '/action/clone';
    this.http.axiosPostWithConfig(cloneURL, this.vms, config).then((res:any)=>{

    })
  }

  template2Vms(csrf, sites, id){

    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }
    let data = {"isTemplate":false}
    let cloneURL = '/service/sites/' + sites + '/vms/' + id;
    this.http.axiosPutWithConfig(cloneURL, data, config).then((res:any)=>{

    })
  }



  // 获取sites列表
  querySitesList(csrf) {

    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }

    this.http.axiosGet('/service/sites',config)
      .then((res: any) => {
        let sites =res.data.sites;
        for (let i =0; i< sites.length; i++){
          let obj = {value: '', label: ''};
          obj.label=sites[i].name;
          obj.value=sites[i].urn;
          this.nzOptionsVmsLocatin.push(obj);
        }

        if(sites.length==1){
          let array = sites[0].urn.split(':');
          this.sites=array[array.length-1];
          this.queryVmsList(this.CSRF_HW, this.sites);
          this.queryOsVersions(this.CSRF_HW, this.sites);
          this.queryClusterList(this.CSRF_HW, this.sites);
          this.queryTemplateList(this.CSRF_HW, this.sites);
         // this.queryDataStores(this.CSRF_HW,this.sites,clusters,hosts)
        }
      })
  }


  // 获取获取集群列表列表
  queryClusterList (csrf, sites) {

    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }

    this.http.axiosGet('/service/sites/' + sites + '/clusters', config)
      .then((res: any) => {
        this.clusters = res.data.clusters;


        for(let i=0;i<this.clusters.length;i++){
          let obj = {title: '', key: '' , children:[]};
          obj.title= this.clusters[i].name;
          obj.key= this.clusters[i].urn;
          let array = this.clusters[i].urn.split(':');
          let clusterId=array[array.length-1]
          this.queryHostList(csrf, sites, clusterId, obj)
        }


      })
  }

  // 获取获取机器列表列表
  queryHostList (csrf, sites, cluster, obj) {
    let arrayResult=[]

    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }

    this.http.axiosGet('/service/sites/' + sites + '/hosts?scope=urn:sites:' + sites + ':clusters:' + cluster, config)
      .then((res: any) => {
        this.hosts = res.data.hosts;
        for(let i=0;i<this.hosts.length;i++){
          let obj = {title: '', key: '', isLeaf: true};
          obj.title=this.hosts[i].name;
          obj.key=this.hosts[i].urn;
          arrayResult.push(obj)
        }
        obj.children=arrayResult;
        this.nzOptionsChooseResource.push(obj);





      })
  }

  // 获取获取机器列表列表
  queryDataStores (csrf, sites, clusters , hosts) {
    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }
    let url = null
     if(clusters != null){
       url = '/service/sites/' + sites + '/datastores?scope=urn:sites:' + sites + ':clusters:' + clusters + '&accessible=1&exceptDatastoreType=LUN'
     }
    if(hosts !=null){
      url = '/service/sites/' + sites + '/datastores?scope=urn:sites:' + sites + ':hosts:' + hosts + '&accessible=1&exceptDatastoreType=LUN'
    }
    this.http.axiosGet(url, config)
      .then((res: any) => {
        this.datastores = res.data.datastores;
        this.listOfData=[]
        for(let i=0;i<this.datastores.length;i++){
          let obj={
            id: i,
            name: '',
            freeSizeGB: 0,
            datastoreUrn: '',
            disabled: false
          }
          obj.name = this.datastores[i].name;
          obj.freeSizeGB = this.datastores[i].freeSizeGB;
          obj.datastoreUrn = this.datastores[i].urn;
          this.listOfData.push(obj);
        }
      })
  }
  // 模板列表
  queryTemplateList (csrf, sites) {

    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }

    this.http.axiosGet('/service/sites/' + sites + '/vms?vmType=0%2C1&isTemplate=true&page=1&offset=0&limit=15', config)
      .then((res: any) => {
        this.listOfTemplate=[]
        let list = res.data.vms;
        for (let i = 0; i < list.length; i++){
          let obj={
            id: 0,
          name: '',
          locationName: '',
          status: '',
          isBindingHost: false ,
          hostName: '',
            urn:'',
          disabled: false
          }
          obj.id = i
          obj.name=list[i].name;
          obj.locationName=list[i].locationName;
          obj.status=list[i].status;
          obj.isBindingHost=list[i].isBindingHost;
          obj.hostName=list[i].hostName;
          obj.urn=list[i].urn
          this.listOfTemplate.push(obj);
        }
      })
  }



    // 模板详情
  queryTemplate(csrf, sites,id) {
    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }

    this.http.axiosGet('/service/sites/' + sites + '/vms/' + id + '?detail=0', config)
      .then((res: any) => {
        this.TemplateInfo.detail = res.data;
        this.vms.name = res.data.name;
        this.chooseResourcValue = res.data.location
        this.vms.description = res.data.description;
        this.vms.isBindingHost = res.data.isBindingHost;
        let array=res.data.urn.split(':')
        this.vms.parentObjUrn = array[0] + ':' + array[1]  + ':' +  array[2]
        this.vms.location = res.data.location;
        this.vms.osOptions = res.data.osOptions;
        this.vms.vmConfig.cpu = res.data.vmConfig.cpu;
        this.vms.vmConfig.memory = res.data.vmConfig.memory;
        this.vms.vmConfig.properties = res.data.vmConfig.properties;
        this.vms.vmConfig.graphicsCard = res.data.vmConfig.graphicsCard;
        this.vms.vmConfig.numaNodes = res.data.vmConfig.numaNodes;
        this.diskList = []
        for(let i = 0; i < res.data.vmConfig.disks.length;i++){
          let obj= {
            "datastoreUrn": "",   //硬盘主机  ???
            "name": "",     //所属数据存储
            "quantityGB": 0,    //硬盘大小
            "sequenceNum": 0,
            "indepDisk": false,
            "persistentDisk": true,
            "isThin": false,
            "pciType": "0",   //总线类型
            "volType": 0,         //类型  磁盘模式
            "bootOrder": 0
          }
          obj.datastoreUrn = res.data.vmConfig.disks[i].datastoreUrn;
          this.datastoreInfo.datastoreUrn=obj.datastoreUrn;
          obj.name = res.data.vmConfig.disks[i].name;
          obj.quantityGB = res.data.vmConfig.disks[i].quantityGB;
          obj.sequenceNum = i + 1
          obj.indepDisk = res.data.vmConfig.disks[i].indepDisk;
          obj.persistentDisk = res.data.vmConfig.disks[i].persistentDisk;
          obj.isThin = res.data.vmConfig.disks[i].isThin;
          obj.pciType = res.data.vmConfig.disks[i].pciType;
          obj.volType = res.data.vmConfig.disks[i].volType;
          obj.bootOrder = res.data.vmConfig.disks[i].bootOrder;
          //this.vms.vmConfig.disks.push(obj);
          this.diskList.push(obj)
        }
        this.nicsList = []
        for(let i = 0; i < res.data.vmConfig.nics.length;i++){
          let obj= {
            "sequenceNum": 0,
            "portGroupName":"",
            "portGroupUrn": "",   //端口组  ???
            "virtIo": 1,   //virtio
            "nicConfig": {
              "vringbuf": 256,     //IO环大小
              "queues": 1       // 队列数:
            },
            "enableSecurityGroup": false,   // 安全组: 未开启
            "bootOrder": -1
          }
          obj.portGroupName = res.data.vmConfig.nics[i].portGroupName;
          obj.sequenceNum = i +  1 ;
          obj.portGroupUrn = res.data.vmConfig.nics[i].portGroupUrn;
          obj.virtIo = res.data.vmConfig.nics[i].virtIo;
          obj.nicConfig = res.data.vmConfig.nics[i].nicConfig;
          obj.enableSecurityGroup = res.data.vmConfig.nics[i].enableSecurityGroup;
          obj.bootOrder = res.data.vmConfig.nics[i].bootOrder;
          //this.vms.vmConfig.nics.push(obj)
          this.nicsList.push(obj)
        }
      })
  }

  // 虚拟机详情
  queryVms(csrf, sites,id) {
    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }

    this.http.axiosGet('/service/sites/' + sites + '/vms/' + id + '?detail=0', config)
      .then((res: any) => {
        let data = res.data;



        this.vms.name = res.data.name;
        this.chooseResourcValue = res.data.location
        this.vms.description = res.data.description;
        this.vms.isBindingHost = res.data.isBindingHost;
        let array=res.data.urn.split(':')
        this.vms.parentObjUrn = array[0] + array[1] + array[2]
        this.vms.location = res.data.location;
        this.vms.osOptions = res.data.osOptions;
        this.vms.vmConfig.cpu = res.data.vmConfig.cpu;
        this.vms.vmConfig.cpu['slotNum'] = 8

        this.vms.vmConfig.memory = res.data.vmConfig.memory;
        this.vms.vmConfig.memory['unit'] = 'GB';


        this.vms.vmConfig.properties.clockMode = res.data.vmConfig.properties.clockMode;
        this.vms.vmConfig.properties.bootFirmware = res.data.vmConfig.properties.bootFirmware;
        this.vms.vmConfig.properties.bootFirmwareTime = res.data.vmConfig.properties.bootFirmwareTime;
        this.vms.vmConfig.properties.bootOption = res.data.vmConfig.properties.bootOption;
        this.vms.vmConfig.properties.evsAffinity = res.data.vmConfig.properties.evsAffinity;
        this.vms.vmConfig.properties.vmVncKeymapSetting = res.data.vmConfig.properties.vmVncKeymapSetting;
        this.vms.vmConfig.properties.isAutoUpgrade = res.data.vmConfig.properties.isAutoUpgrade;
        this.vms.vmConfig.properties.attachType = res.data.vmConfig.properties.attachType;
        this.vms.vmConfig.properties.isEnableMemVol = res.data.vmConfig.properties.isEnableMemVol;
        this.vms.vmConfig.properties.isEnableFt = res.data.vmConfig.properties.isEnableFt;
        this.vms.vmConfig.properties.cdRomBootOrder = res.data.vmConfig.properties.cdRomBootOrder;
        this.vms.vmConfig.properties.consoleLogTextState = res.data.vmConfig.properties.consoleLogTextState;
        this.vms.vmConfig.properties.isAutoAdjustNuma = res.data.vmConfig.properties.isAutoAdjustNuma;
        this.vms.vmConfig.properties.secureVmType = res.data.vmConfig.properties.secureVmType;
        this.vms.vmConfig.properties.dpiVmType = res.data.vmConfig.properties.dpiVmType;
        this.vms.vmConfig.properties.consolelog = res.data.vmConfig.properties.consolelog;


        this.vms.vmConfig.graphicsCard = res.data.vmConfig.graphicsCard;
        this.vms.vmConfig.numaNodes = res.data.vmConfig.numaNodes;
        this.vms.floppyProtocol='unMount'
        this.diskList = []
        for(let i = 0; i < res.data.vmConfig.disks.length;i++){
          let obj= {
            "datastoreUrn": "",   //硬盘主机  ???
            "name": "",     //所属数据存储
            "quantityGB": 0,    //硬盘大小
            "sequenceNum": 0,
            "indepDisk": false,
            "persistentDisk": true,
            "isThin": false,
            "pciType": "0",   //总线类型
            "volType": 0,         //类型  磁盘模式
            "bootOrder": 0,
            "systemVolume": true,
          }
          obj.datastoreUrn = res.data.vmConfig.disks[i].datastoreUrn;
          this.datastoreInfo.datastoreUrn=obj.datastoreUrn;
          obj.name = res.data.vmConfig.disks[i].datastoreName;
          obj.quantityGB = res.data.vmConfig.disks[i].quantityGB;
          obj.sequenceNum = i + 1
          obj.indepDisk = res.data.vmConfig.disks[i].indepDisk;
          obj.persistentDisk = res.data.vmConfig.disks[i].persistentDisk;
          obj.isThin = res.data.vmConfig.disks[i].isThin;
          obj.pciType = res.data.vmConfig.disks[i].pciType;
          obj.volType = res.data.vmConfig.disks[i].volType;
          obj.bootOrder = res.data.vmConfig.disks[i].bootOrder;
          this.diskList.push(obj)
        }
        this.nicsList = []
        for(let i = 0; i < res.data.vmConfig.nics.length;i++){
          let obj= {
            "sequenceNum": 0,
            "portGroupName":"",
            "portGroupUrn": "",   //端口组  ???
            "virtIo": 1,   //virtio
            "nicConfig": {
              "vringbuf": 256,     //IO环大小
              "queues": 1       // 队列数:
            },
            "enableSecurityGroup": false,   // 安全组: 未开启
            "bootOrder": -1
          }
          obj.portGroupName = res.data.vmConfig.nics[i].portGroupName;
          obj.sequenceNum = i +  1 ;
          obj.portGroupUrn = res.data.vmConfig.nics[i].portGroupUrn;
          obj.virtIo = res.data.vmConfig.nics[i].virtIo;
          obj.nicConfig = res.data.vmConfig.nics[i].nicConfig;
          obj.enableSecurityGroup = res.data.vmConfig.nics[i].enableSecurityGroup;
          obj.bootOrder = res.data.vmConfig.nics[i].bootOrder;
          this.nicsList.push(obj)
        }



      })
  }

  // 分布式交换机列表
  queryDvSwitchs (csrf, sites, host) {

    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }

    this.http.axiosGet('/service/sites/' + sites + '/dvswitchs?location=urn%3Asites%' + sites + '%3Ahosts%3A' + host, config)
      .then((res: any) => {
        this.dvSwitchs = res.data.dvSwitchs;
      })
  }


  // 端口列表
  queryPortGroups (csrf, sites) {
    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }

    this.http.axiosGet('/service/sites/' + sites + '/dvswitchs/1/portgroups?limit=5&offset=0', config)
      .then((res: any) => {
        this.portGroups = res.data.portGroups;
        for(let i=0;i<this.portGroups.length;i++){
        let obj=  {
            id: i,
            name: '',
            portType: 0,
            nicsUrn: '',
            disabled: false
          }
          obj.name=this.portGroups[i].name;
          obj.portType=this.portGroups[i].portType;
          obj.nicsUrn=this.portGroups[i].urn;
          this.listOfNicsData.push(obj);
        }
      })
  }


  // 获取虚拟机列表
  queryVmsList(csrf,sites) {

    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
         'Accept-Language': 'zh-CN'
      }
    }

    this.http.axiosGet('/service/query/sites/' + sites + '/vms/action/queryVmsList?detail=2&isTemplate=false&queryFlag=normal&orderField=name&order=DESC&limit=15&offset=0',config)
      .then((res: any) => {
       console.info(res.data);
       for(let i=0;i<res.data.vms.length;i++){
         let obj={
           'virtualTitle':'',
           'virtualStaus':'',
           'startTime':'',
           'urn':'',
           'id':0,
           'arch':'',
           'ip':'',
           'clusterName':'',
           'hostName':'',
           isBindingHost:''
         };
         obj.virtualTitle = res.data.vms[i].name
         obj.virtualStaus = res.data.vms[i].status
         obj.startTime = res.data.vms[i].createTime
         // obj.endTime=res.data.vms[i].status
         obj.id = i
         obj.urn = res.data.vms[i].urn
         obj.arch = res.data.vms[i].arch
         obj.ip = res.data.vms[i].ip
         obj.clusterName = res.data.vms[i].clusterName
         obj.hostName = res.data.vms[i].hostName
         obj.isBindingHost=res.data.vms[i].isBindingHost
         this.virtualList.push(obj)
       }

       console.error(this.virtualList)


      })
  }

  // 端口列表
  queryOsVersions (csrf, sites) {

    let config = {
      headers: {
        'CSRF-HW': csrf,
        'Accept': 'application/json;version=8.0;charset=UTF-8',
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept-Language': 'zh-CN'
      }
    }

    this.http.axiosGet('/service/sites/' + sites + '/vms/osversions', config)
      .then((res: any) => {
        for(let i=0;i<res.data.linux.length;i++){
          let obj={label:'',value:''};
          obj.label=res.data.linux[i].versionDes
          obj.value=res.data.linux[i].id
          this.linuxVersions.push(obj)
        }
        for(let i=0;i<res.data.windows.length;i++){
          let obj={label:'',value:''};
          obj.label=res.data.windows[i].versionDes
          obj.value=res.data.windows[i].id
          this.windowsVersions.push(obj)
        }
        for(let i=0;i<res.data.other.length;i++){
          let obj={label:'',value:''};
          obj.label=res.data.other[i].versionDes
          obj.value=res.data.other[i].id
          this.otherVersions.push(obj)
        }

        this.osList=this.windowsVersions;
      })
  }

  setOs(val){
    if(1==val){
      this.osList=this.windowsVersions;
    }
    if(2==val){
      this.osList=this.linuxVersions;
    }
    if(3==val){
      this.osList=this.otherVersions;
    }
  }
 //当前方法暂停5秒

  // 请求验证码
/*  getVerify() {
      this.http.axiosGet('/service/verify')
        .then((res: any) => {


          let verfyNmae= res.imageName
          let url='/verifycodeimg/'+verfyNmae
          this.VerifyCodeImage=url
      })
  }*/


  // 请求验证码
  getVerify() {
    this.http.axiosGet('/service/verify',null)
      .then((res: any) => {
        let verfyNmae= res.data.imageName
        let url='/verifycodeimg/'+verfyNmae
        this.VerifyCodeImage =url
      })
  }


  // 提示信息关闭按钮
  shutWaring(): void{
    this.waringShow = false;
    console.log('点击了关闭');
  }

  showModal(): void {
    this.isVisible = true;
  }
  showNicsModal(index): void {
  this.nicsIsVisible = true;
  this.nicsIndex = index ;
}

  showTemplateModal(): void {
    this.templateIsVisible = true;
  }
  showVmsModal(): void {
    this.vmsIsVisible = true;
  }
  handleOk(): void {
    console.log('Button ok clicked!');
    //创建虚拟机
    if ( this.virtualType == 1){
      this.createVms(this.CSRF_HW, this.sites);
    }
    if( this.virtualType == 2){
      this.cloneVmsByTemplate(this.CSRF_HW, this.sites, this.templateId);
    }
    if( this.virtualType == 3){
      this.cloneVms(this.CSRF_HW, this.sites, this.vmsId);
    }

    if( this.virtualType == 5){
      this.template2Vms(this.CSRF_HW, this.sites, this.templateId);
    }

    this.isVisible = false;
  }


  addType(): void {

   if (this.addTypeValue == '1'){
   let disk ={
       datastoreUrn: this.datastoreInfo.datastoreUrn,   //硬盘主机
         name: "",     //所属数据存储
         quantityGB: 0,    //硬盘大小
         sequenceNum: 1,
         indepDisk: false,
         persistentDisk: true,
         isThin: false,
         pciType: "VIRTIO",   //总线类型
         volType: 1,         //类型  磁盘模式
         bootOrder: -1
     }
     this.diskList.push(disk)
   }
   if (this.addTypeValue == '2'){
     let nic = {
       name: '',
       sequenceNum: 0,
       portGroupUrn: "",   //端口组
       virtIo: 1,   //virtio
       nicConfig: {
         vringbuf: 256,     //IO环大小
         queues: 1       // 队列数:
       },
       enableSecurityGroup: false,   // 安全组: 未开启
       bootOrder: -1
     }
    this.nicsList.push(nic)
    }
    this.addTypeValue = 'null'
}

  removeItem(index, val): void {
    //删除选中的选项
    val.splice(index, 1);
  }
  handleNicsOk(): void {
    console.log('Button ok clicked!');
    this.nicsIsVisible = false;
  }
  handleTemplateOk(): void {
    console.log('Button ok clicked!');
    this.templateIsVisible = false;
  }

  handleVmsOk(): void {
    console.log('Button ok clicked!');
    this.vmsIsVisible = false;
  }
  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }
  handlNicsCancel(): void {
    console.log('Button cancel clicked!');
    this.nicsIsVisible = false;
  }
  lastStep(): void {
    this.virtualStep=this.virtualStep-1
    if(this.virtualStep==1)
      this.virtualStep=1
  }


  nextStep(): void {


    if(this.virtualStep==4 || (this.virtualStep==3 && this.virtualType==3)) {
      //保存磁盘信息
      this.vms.vmConfig.disks = []
      for ( let i = 0; i < this.diskList.length; i++){
        this.diskList[i].sequenceNum = i+1 ;
        this.diskList[i].datastoreUrn =  this.datastoreInfo.datastoreUrn;
      }

      this.vms.vmConfig.disks = this.diskList;

     /* let obj={
        datastoreUrn: this.datastoreInfo.datastoreUrn,   //硬盘主机
        name: this.datastoreInfo.name,     //所属数据存储
        quantityGB: this.quantityGB,    //硬盘大小
        sequenceNum: 1,
        indepDisk: false,
        persistentDisk: true,
        isThin: false,
        pciType: "VIRTIO",   //总线类型
        volType: 1,         //类型  磁盘模式
        bootOrder: -1
      }
      this.vms.vmConfig.disks.push(obj)*/

      this.vms.vmConfig.nics = [];
      for ( let i = 0; i < this.nicsList.length; i++){
        this.nicsList[i].sequenceNum = i;
      }
      this.vms.vmConfig.nics = this.nicsList;

     /* let nic ={
        sequenceNum: 0,
        portGroupUrn: this.nicsInfo.portGroupUrn,   //端口组
        virtIo: 1,   //virtio
        nicConfig: {
        vringbuf: 256,     //IO环大小
          queues: 1       // 队列数:
      },
        enableSecurityGroup: false,   // 安全组: 未开启
        bootOrder: -1
      }
      this.vms.vmConfig.nics.push(nic);*/
    }
    if(this.virtualStep==7){
      this.virtualStep=1
    }

   /* if(this.virtualType==2&&this.virtualStep==2){
      this.virtualStep=this.virtualStep+2
    }else{
      this.virtualStep=this.virtualStep+1
    }*/
    this.virtualStep=this.virtualStep+1


  }



  updateCheckedSet(id: number, checked: boolean , val): void {
    if (checked) {
      val.add(id);
    } else {
      val.delete(id);
    }
  }

  onCurrentPageDataChange(listOfCurrentPageData: ReadonlyArray<Data>): void {
    this.listOfCurrentPageData = listOfCurrentPageData;
    //this.refreshCheckedStatus();
  }

  refreshCheckedStatus(val): void {
    const listOfEnabledData = this.listOfCurrentPageData.filter(({ disabled }) => !disabled);
    this.checked = listOfEnabledData.every(({ id }) => val.has(id));
    this.indeterminate = listOfEnabledData.some(({ id }) => val.has(id)) && !this.checked;
  }

  onItemChecked(id: number, checked: boolean, val): void {

    if(val.size==0){
      this.updateCheckedSet(id, checked, val);
      this.refreshCheckedStatus(val);
    }else{
      val.clear();
      this.updateCheckedSet(id, checked, val);
      this.refreshCheckedStatus(val);
    }
    this.datastoreInfo.datastoreUrn = this.listOfData[id].datastoreUrn;
    this.datastoreInfo.name = this.listOfData[id].name;

  }


  onItemCheckedNics(id: number, checked: boolean, val): void {
    if(val.size==0){
      this.updateCheckedSet(id, checked, val);
      this.refreshCheckedStatus(val);
    }else{
      val.clear();
      this.updateCheckedSet(id, checked, val);
      this.refreshCheckedStatus(val);
    }
    this.nicsInfo.name = this.listOfNicsData[id].name;
    this.nicsInfo.portGroupUrn  = this.listOfNicsData[id].nicsUrn;

    this.nicsList[this.nicsIndex].portGroupName = this.listOfNicsData[id].name;
    this.nicsList[this.nicsIndex].portGroupUrn = this.listOfNicsData[id].nicsUrn;

  }

  onItemCheckedTemplate(id: number, checked: boolean, val): void {
    if(val.size==0){
      this.updateCheckedSet(id, checked, val);
      this.refreshCheckedStatus(val);
    }else{
      val.clear();
      this.updateCheckedSet(id, checked, val);
      this.refreshCheckedStatus(val);
    }

    this.TemplateInfo.name = this.listOfTemplate[id].name;
    this.TemplateInfo.urn  = this.listOfTemplate[id].urn;
    let array = this.listOfTemplate[id].urn.split(':');
    this.templateId = array[array.length-1]
    this.queryTemplate(this.CSRF_HW, this.sites, array[array.length-1])


    this.onChange(null);
  }

  onVmsChecked(id: number, checked: boolean, val): void {
    if(val.size==0){
      this.updateCheckedSet(id, checked, val);
      this.refreshCheckedStatus(val);
    }else{
      val.clear();
      this.updateCheckedSet(id, checked, val);
      this.refreshCheckedStatus(val);
    }

    this.vms.name = this.virtualList[id].name;
    this.vms.parentObjUrn  = this.virtualList[id].urn;
    let array = this.vms.parentObjUrn.split(':');
    this.vmsId = array[array.length-1]
    this.queryVms(this.CSRF_HW, this.sites, array[array.length-1])
  }

  onAllChecked(checked: boolean): void {
    this.listOfCurrentPageData.filter(({ disabled }) => !disabled).forEach(({ id }) => this.updateCheckedSet(id, checked,null));
    this.refreshCheckedStatus(null);
  }



  setVirtualType(type): void{
    this.virtualType = type;
    if (type === 1) {
      this.createType = '创建新虚拟机';
    }else if (type === 2) {
       this.createType = '使用模板部署虚拟机';
    }else if (type === 3) {
       this.createType = '虚拟机克隆为虚拟机';
    }else if (type === 4) {
       this.createType = '导入虚拟机';
    }else {
       this.createType = '模板转为虚拟机';
    }
  }
  log1(value: { label: string; value: string; age: number }): void {
    console.log(value);
    this.vmsLocationLabel = value.label;
  }

  onChange($event: string): void {
    this.vms.location=this.chooseResourcValue
    let array=this.chooseResourcValue.split(':');
    if(array[3]=='clusters'){
      this.queryDataStores(this.CSRF_HW, this.sites, array[4], null);
    }else{
      this.queryDataStores(this.CSRF_HW, this.sites, null, array[4]);
    }
    // this.queryDataStores(this.CSRF_HW,this.sites,clusters,hosts)

    this.queryPortGroups(this.CSRF_HW, this.sites);

    //this.chooseResourcValueLabel = $event.title
  }
  onChooseChange(): void{

  }

}
